<?php
/**
 * beimuaihui System
 * Copyright(c) 2011-2020 beimuaihui.
 * @license    http://www.gnu.org/licenses/gpl.html     This software Under GPL V3 License
 * beimuaihui@gmail.com
 * http://code.google.com/p/beimuaihui/
 * $Id: UserController.php 465 2012-02-12 05:33:23Z beimuaihui $
 */



class System_UserController extends Baogg_Controller_Action {
	public $user;
	function init() {
		Zend_Loader::loadClass ( 'User' );
		$this->user = new User ( );

	}

	/**
	 * The default action
	 */
	public function listAction() {
		global $LANG;

		$params=$this->getRequest()->getParams();
		$form_url=$params;

		Zend_Loader::loadClass("Baogg_View_Extgrid");

		$cm=array();
		$cm['user_id']=array("hidden"=>true,"cmType"=>Baogg_View_Extgrid::CMTYPE_PK) ;
		$cm['user_name']=array("sortable"=>true);
		$cm['user_logname']=array("sortable"=>true);
		//$cm['role_id']=array("sortable"=>true);
		$cm['user_group_id']=array("hidden"=>true);
		//$cm['city_id']=array("sortable"=>true);
		//$cm['user_level_id']=array("sortable"=>true);
		$cm['phone']=array("sortable"=>false);
		$cm['address']=array("sortable"=>true);
		$cm['email']=array("sortable"=>true);
		//$cm['mobile']=array("sortable"=>false);
		$cm['state']=array("hidden"=>true);
		$cm['state2']=array("sortable"=>true);
		$cm['gender']=array("hidden"=>true);
		$cm['birthday']=array("hidden"=>true);
		$cm['education']=array("hidden"=>true);
		$cm['party_time']=array("hidden"=>true);
		$cm['duty']=array("hidden"=>true);
		$cm['nation']=array("hidden"=>true);
		$cm['birthplace']=array("hidden"=>true);
		$cm['political']=array("hidden"=>true);
		$cm['graducated']=array("hidden"=>true);


		$cols=$this->user->info(User::COLS);
		foreach($cols as $col){
			if(!isset($cm[$col])){
				$cm[$col]=array("hidden"=>true);
			}
		}
		//get user info model
		/*$model=new Model();
		 $permission=new Permission();
		$user=new User();
		$rs_model=$model->getList(array("main_table"=>"user","state"=>1), array("sort"=>"ordering","dir"=>"asc"));
		foreach((array)$rs_model as $v){
		$arr_group_id=$permission->checkModel($v['model_id']);

		if(!$user->isAdmin() && !$arr_group_id){
		continue;
		}
		//echo '<pre>';var_dump($arr_group_id);exit;
		$cm[$v['ext_table']]=array("sortable"=>false,"header"=>$v['model_name']);
		}*/
		// $store_user_group_id =array(array(1,2));
		//$cm['action']=array("sortable"=>false);
		//$cm['sub_table']=array("hidden"=>true,"cmType"=>Baogg_View_Extgrid::CMTYPE_SUBTABLE) ; //Baogg_View_Extgrid::;


		$form_url['action']="data";
		$grid=new Baogg_View_Extgrid($form_url, $cm);
		$grid->setSelectionModel(true);
		$grid->setRowNumberer(true);

		$Resource=new Resource();
		$rs_subject=$Resource->getList(array('resource_code'=>'user'));
		$this->getRequest()->setParam('subject_id', @$rs_subject[0]['resource_id']);
		$rs_resource=$Resource->getList(array('resource_code'=>'qa_report'));
		$this->getRequest()->setParam('resource_id', @$rs_resource[0]['resource_id']);
		$grid->addExistButtons(array('add','remove','query'),array('edit','delete','user_group_role','user_permission'));
		//$grid->registerButton("fields","window.location.href='".BAOGG_BASE_URL."system/userfield/list/';");

		//$this->view->form_url=BAOGG_BASE_URL."system/user/save";


		if($_SESSION['admin']['user_group_role']['user_group_id']){
			$user_group_id=(array)$_SESSION['admin']['user_group_role']['user_group_id'];
		}else{
			$user_group_id=array($_SESSION['admin']['user']['user_group_id']);
		}

		$this->view->LANG=Zend_Json::encode($LANG);
		$this->view->grid = $grid->render();

		$UserGroup=new UserGroup();
		$store_user_group_id=$UserGroup->getComboTree(array("user_group_id"=>$user_group_id),NULL,NULL,array("user_group_id","user_group_name","user_group_pid"));

		$Role=new Role();
		$store_role_id=$Role->getComboTree(array("state"=>1),NULL,NULL,array("role_id","role_name","role_pid"));


		$form_url['action']='add';
		$form=new Baogg_View_Extform(array("url"=>$form_url,"height"=>350,"width"=>600));

		//$form=new Baogg_View_Extform(array("height"=>220));
		$form->addItem(0,array('name'=>'user_logname','allowBlank'=>false));
		$form->addItem(0,array('name'=>'user_name','allowBlank'=>false));
		$form->addItem(0,array('name'=>'password','inputType'=>'password'));
		$form->addItem(0,array('name'=>'user_group_id','value'=>@$user_group_id[0],'xtype'=>'combo','store'=>$store_user_group_id));
		//$form->addItem(0,array('name'=>'role_id','xtype'=>'combo','store'=>$store_role_id));

		//$form->addItem(0,array('name'=>'gender','xtype'=>'radiogroup','source'=>BAOGG_LANGUAGE::array2store('arr_gender')));
		//$form->addItem(0,array('name'=>'birthday','xtype'=>'datefield','format'=>'Y-m'));

		$form->addItem(1,array('name'=>'phone'));
		$form->addItem(1,array('name'=>'address'));
		$form->addItem(1,array('name'=>'email'));
		//$form->addItem(1,array('name'=>'msn'));
		//$form->addItem(1,array('name'=>'qq'));
		//$form->addItem(1,array('name'=>'nation'));
		//$form->addItem(1,array('name'=>'birthplace'));
		//$form->addItem(1,array('name'=>'political'));
		//$form->addItem(2,array('name'=>'graduated'));


		//$form->addItem(2,array('name'=>'education','xtype'=>'combo','store'=>BAOGG_LANGUAGE::array2store('arr_education')));
		//$form->addItem(2,array('name'=>'party_time','xtype'=>'datefield'));
		//$form->addItem(2,array('name'=>'work_time','xtype'=>'datefield'));
		$form->addItem(2,array('name'=>'ordering'));
		$form->addItem(2,array('name'=>'state','xtype'=>'radiogroup','source'=>BAOGG_LANGUAGE::array2store("arr_state")));
		//$form->addItem(2,array('name'=>'user_group_id',"xtype"=>"hidden","hideLabel"=>true,'value'=>$user_group_id));
		$form->addItem(2,array('name'=>'user_id',"xtype"=>"hidden","hideLabel"=>true));
		//$form->addExistButtons(array('search','add','edit','delete','remove','user_group_role','reset'),array('edit','delete','user_group_role'));
		$form->addExistButtons(array('-','save_grid','save_new','save','-','search','-','cancel'));//,'config','config'
			
		$this->view->form=$form;




	}

	/**
	 * The data action
	 */
	function dataAction() {
		global $LANG;
	  
		$condition=$this->_buildWhere();
		extract($condition);

		$rs=$this->user->getList($where,$order,$limit);
		$cnt=$this->user->getList($where,null,null,"count(*) as cnt");

		foreach((array)$rs as $k=>$v){
			$rs[$k]['password']='#unchanged#';
			$arr_state=Baogg_Language::get('arr_state');
			$rs[$k]['state2']=$arr_state[$v['state']];
			/*$model=new Model();
			 $permission=new Permission();
				
			$arr_row_id=$permission->checkResource('model');
			$arr_model_id=array_keys($arr_row_id);
			$rs_model=$model->getList(array("main_table"=>"user","state"=>1,"model_id"=>$arr_model_id), array("sort"=>"ordering","dir"=>"asc"));
			foreach((array)$rs_model as $model){
			//echo '<pre>';print_r($model);exit;
			$ModelTable=new ModelTable($model['model_id']);
			try{
			$rs_model_table=$ModelTable->getList(array("user_id"=>(int)$v['user_id']), NULL, NULL,"count(*) as cnt");
			$cls=@$rs_model_table[0]['cnt']==0?"gray":"";
			}catch(Exception $e){
			$cls="";
			}
			$icon='<img class="'.$cls.'"  src="'.BAOGG_UPLOAD_URL."image/menu/".$model['ext_table'].'.png'.'" />';
			$icon='<a href="javascript:(function(){var menu=top.Ext.getCmp(\'menu_content_'.$model['model_id'].'\').initialConfig;menu.url=\''.BAOGG_BASE_URL. 'mall/userinfo/list/model_id/'.$model['model_id'].'/user_id/'.$v['user_id'].'\';top.addTab(menu);})()">'.$icon.'</a>';//$v['user_group_id']

			if($user->isAdmin() || in_array($v['user_group_id'],$arr_group_id) || (in_array(0,$arr_group_id) && $v['user_id']==$_SESSION['admin']['user']['user_id'])){
			//$icon='<a href="'.BAOGG_BASE_URL. 'mall/userinfo/list/model_id/'.$model['model_id'].'/user_group_id/'.$v['user_group_id'].'/user_id/'.$v['user_id'].'">'.$icon.'</a>';
			 
			}
			$rs[$k][$model['ext_table']]=$icon;

			}*/
			 

		}
		//echo Baogg_Db::debugDb(Zend_Registry::get('db'));print_r($cnt);exit;
		$this->view->grid = Zend_Json::encode(array("count"=>$cnt[0]['cnt'],"data"=>$rs));
	}


	/**
	 * The add action
	 */
	function addAction(){
		$this->saveAction();
	}

	/**
	 * The edit action
	 */
	function editAction() {
		$this->saveAction();
	}

	/**
	 * The delete action
	 */
	function deleteAction() {

		$ret=array("success"=>false,"msg"=>"delete_fail");
		$id = Baogg_Controller_Action::_getParam ( 'ids' );
			
		 

		if ($this->user->_delete ( $id )){
			$ret['success'] = true;
			$ret["msg"]="delete_ok";
		}

		echo Baogg_Language::outputResult($ret);
		$this->_helper->viewRenderer->setNoRender ();
	}

	function removeAction()
	{
		$this->deleteAction();
	}
	/**
	 * The save action
	 */
	function saveAction() {
		//global $LANG;

		$ret=array("success"=>false,"msg"=>"save_fail");
	  
		//check form
		if (!$this->_request->isPost ())
		{
			echo Baogg_Language::outputResult($ret);
			exit;
		}

		$formData = $this->_request->getPost ();

		if(!$formData)
		{
			echo Baogg_Language::outputResult($ret);
			exit;
		}

		$action=$this->getRequest()->getParam('action');
		$arr=$this->user->filterForm($formData);
		foreach((array)$arr as $k=>$v){
			if($k=='password' && $v=='#unchanged#'){
				unset($arr[$k]);
			}
		}

		$rs = $this->user->getSame($arr);
		if($action=='edit'){

			if(count($rs)==0 ||  count($rs)==1 &&  $rs[0] == $arr["user_id"] ){
				$this->user->_update($arr,$arr["user_id"]);
				$ret['success'] = true;
				$ret['msg'] = "save_ok";
			}else{
				$ret['msg'] = "exist_same_record";
			}
				
		}else{
			//insert record
			//$permission_type = 1;
			if($rs){
				$ret['msg'] = "exist_same_record";
			}else{
				unset($arr["user_id"]);
				$user_id=$this->user->_insert($arr);
				$ret['success'] = $user_id>0?true:false;

				//add default role id
				$UserGroupRole=new UserGroupRole();
				$UserGroupRole->addDefaultRole($user_id);

				$ret['msg'] = "add_ok";
			}
		}
		//echo Baogg_Db::debugDb(Zend_Registry::get("db"));
		echo Baogg_Language::outputResult($ret);

		$this->_helper->viewRenderer->setNoRender ();


	}

	function usergrouproleAction()
	{
		global $LANG;

		$form_data=$this->getRequest()->getParams();
		if($this->getRequest()->isPost() && $form_data['user_id'] && $form_data['user_group_id']){
			Zend_Loader::loadClass('UserGroupRole');
			$UserGroupRole=new UserGroupRole();
			$flag=true;
				
			$user_id=(int)$form_data['user_id'];
			$UserGroupRole->reset($user_id);
			foreach((array)$form_data['user_group_id'] as $user_group_id=>$v){
				$role_id=@$form_data['role_id'][$user_group_id];
				if($user_group_id===NULL || $role_id===NULL){
					continue;
				}


				//auto include sub group
				/*if($_POST['include_sub_group'] && $user_group_id)	{
					$Usergroup=new UserGroup();
				$arr_user_group_id=$Usergroup->getWithChildIds(array($user_group_id));
				foreach((array)$arr_user_group_id as $sub_user_group_id){
				$row=array("user_id"=>$user_id,"user_group_id"=>$sub_user_group_id,"role_id"=>$role_id);
				$UserGroupRole->_insert($row);
				}
				}else{*/
				foreach((array)$role_id as $_row_id){
					$row=array("user_id"=>$user_id,"user_group_id"=>$user_group_id,"role_id"=>$_row_id);
					$flag= $UserGroupRole->_insert($row) && $flag;
				}


				//}
					
			}
			$ret['success'] = $flag;
			$ret['msg'] = $flag?"save_ok":"save_fail";
			echo Baogg_Language::outputResult($ret);
			//echo '<pre>';print_r($form_data);echo Baogg_Db::debugDb(Zend_Registry::get('db'));
			$this->_helper->viewRenderer->setNoRender ();
				
		}

		$user_id=$this->getRequest()->getParam('user_id');


		$dbTree=new Baogg_Db_Tree();
		$UserGroupRole=new UserGroupRole();
		$User=new User();

		$grant_user_id=$_SESSION['admin']['user']['user_id'];
		$rs_user_group_role=$UserGroupRole->getList(array("user_id"=>(int)$grant_user_id));
		$arr_grant_group=array();
		$arr_grant_role=array();
		$arr_grant_group_role=array();
		foreach((array)$rs_user_group_role as $v){
			$arr_grant_group[]=$v['user_group_id'];
			$arr_grant_role[]=$v['role_id'];
			$arr_grant_group_role[$v['user_group_id']][$v['role_id']]=1;
		}


		$UserGroup=new UserGroup();
		$where=array("state"=>1);
		if(!$User->isAdmin()){
			$where['user_group_id']=$arr_grant_group;
		}
		$tr_user_group=$UserGroup->getTree($where,null,null,array("user_group_id","user_group_name","user_group_pid","level_id"));




		$role=new Role();
		$where=array("state"=>1);
		if(!$User->isAdmin()){
			$where['role_id']=$arr_grant_role;
		}
		$rs_role=$role->getList($where,array("sort"=>"ordering","dir"=>"asc"));


		$rs_user_group_role=$UserGroupRole->getList(array("user_id"=>(int)$user_id));
		$arr_user_group_role=array();
		foreach((array)$rs_user_group_role as $v){
			if($User->isAdmin() || isset($arr_grant_group_role[$v['user_group_id']][$v['role_id']])){
				$arr_user_group_role[$v['user_group_id']][$v['role_id']]=1;
			}
		}


		$this->view->user_groups=$tr_user_group;
		$this->view->roles=$rs_role;
		$this->view->user_group_roles=$arr_user_group_role;
		//echo '<pre>';print_r($rs_user_group_role);exit;
		$this->view->LANG=$LANG;
		$this->view->user_id=$user_id;
		$this->view->form_url=BAOGG_BASE_URL.$this->getRequest()->getParam('module').'/'.$this->getRequest()->getParam('controller').'/'.$this->getRequest()->getParam('action');
		//echo '<pre>';print_r($tr_user_group);print_r($rs_role);exit;
	}

	function loginAction()
	{
		global $LANG;


		$ret=array("success"=>false,"msg"=>"log_fail");

		//$ReCaptcha = new Zend_Service_ReCaptcha(BAOGG_RECAPTCHA_PUB, BAOGG_RECAPTCHA_PRIV);
		if(!$this->getRequest()->isPost()){
			unset($_SESSION);
			$this->view->form_url="";
			$this->view->LANG=$LANG;
			// $this->view->recaptcha=$ReCaptcha->getHTML();
		}else{
			$params=$this->getRequest()->getParams();
			/* $result = $ReCaptcha->verify(
				$params['recaptcha_challenge_field'],
				$params['recaptcha_response_field']
			); */
			//$result->isValid()
			if (true) {
				$user=$this->user->getList(array("state"=>1,"user_logname"=>$params['log_name']));
				if($user && $user[0]['password']==$params['log_pass']){
					$ret['success']=true;
					$ret['msg']='';
					$_SESSION['admin']['user']=$user[0];
				}
			}
			echo Baogg_Language::outputResult($ret);
			$this->_helper->viewRenderer->setNoRender ();
		}
	}

	function userinfoAction()
	{
		global $LANG;
	}

	function storeAction(){
		global $LANG;
	  
		$condition=$this->_buildWhere();
		extract($condition);

		$rs=$this->user->getList($where,$order,$limit);
		foreach((array)$rs as $k=>$v){
			$rs[$k]['password']='#unchanged#';
		}
		$cnt=$this->user->getList($where,null,null,"count(*) as cnt");

		echo Zend_Json::encode(array("count"=>$cnt[0]['cnt'],"data"=>$rs));

		$this->_helper->viewRenderer->setNoRender ();

	}
	function _buildWhere(){

		$post=$this->_request->getParams ();
		unset($post['password']);
		$where=array();$order=array();$limit=array();
		foreach((array)$post as $k=>$v){
			if($k=='query'){
				if((int)$v==$v){
					$k='user_id';
					$v=(int)$v;
				}else{
					$k='user_name';
				}
			}
			if($k=="start" || $k=="limit"){
				$limit[$k]=$v;
			}else if($k=="sort" || $k=="dir"){
				$order[$k]=$v;
			}else{
				if(in_array($k,array("user_id","user_group_id"))){
					if($v && is_numeric($v)){
						$v=(int)$v;
						$where[$k]=$v;
					}
				}else{
					$v='%'.$v.'%';
					$where[$k]=$v;
				}

			}
		}

		if(!$_SESSION['admin']['user_group_role']['user_group_id']){
			$where['user_id']=(int)$_SESSION['admin']['user']['user_id'];
		}else{
			$where['user_group_id']=(array)$_SESSION['admin']['user_group_role']['user_group_id'];
		}
		return array("where"=>$where,"order"=>$order,"limit"=>$limit);
	}

}
